package com.lut.edu.apm.payCenter.pay;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeQueryModel;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.lut.edu.apm.payCenter.config.AlipayConfig;
import com.lut.edu.apm.payCenter.services.UserOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 支付/订单 查询
 *
 * @author Zhao Suzhen
 * @date `2024/4/15`
 */
@RestController
@RequestMapping("/pay")
public class PayQueryController {
    @Autowired
    UserOrderService userOrderService;

    /**
     * 查询订单信息
     *
     * @param outTradeNo 订单编号
     * @return
     * @throws Exception
     */
    @PostMapping("queryPay")
    @ResponseBody
    public String showPay(@RequestParam("out_trade_no") String outTradeNo) throws Exception {
        HashMap<String, Object> result = new HashMap<>();
        // 初始化SDK
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        AlipayTradeQueryModel model = new AlipayTradeQueryModel();
        model.setOutTradeNo(outTradeNo);
        request.setBizModel(model);
        AlipayTradeQueryResponse response = alipayClient.execute(request);
        if (response.isSuccess()) {
            result.put("isSuccess", 200);
            String tradeStatus = response.getTradeStatus();
            // 交易成功
            if ("TRADE_SUCCESS".equals(tradeStatus)) {
                userOrderService.modifyStatus(outTradeNo, 1);
            }
            result.put("trade_status", tradeStatus);
        } else {
            result.put("isSuccess", 401);
        }
        return JSONObject.toJSONString(result);
    }

    /**
     * 客流量折线图数据
     *
     * @return
     */
    @GetMapping("orderCountToDay")
    @ResponseBody
    public String orderCountToDay() {
        List<Map<String, Object>> orderCount = userOrderService.queryOrderCountByDay();
        Map<String, Object> result = new HashMap<>();
        // 对时间每六个小时分组
        Map<String, Long> data = orderCount.stream()
                .collect(Collectors.groupingBy(
                        map -> {
                            Timestamp gmtCreated = (Timestamp) map.get("gmt_created");
                            Instant instant = gmtCreated.toInstant();
                            LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
                            return String.valueOf(localDateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli() / 3600000);
                        },
                        Collectors.counting()
                ));
//        List<String> xAxis = new ArrayList<>();
//        List<Long> yAxis = new ArrayList<>();
        Map<String, Object> axis = new HashMap<>();
        // 将时间格式化并添加到横轴，数量做纵轴
        data.forEach((key, value) -> {
            String hours = key;
            Instant epoch = Instant.EPOCH;
            Duration startDuration = Duration.ofHours(Long.parseLong(hours));
            // 创建一个表示12小时的Duration对象, 用于加8个小时，时间校准
            Duration duration = Duration.ofHours(8);
            Instant start = epoch.plus(startDuration).plus(duration);
//            Duration endDuration = Duration.ofHours(Long.parseLong(hours[1]));
//            Instant end = epoch.plus(endDuration).plus(duration);
            axis.put(start.toString().substring(11, 13) + "时", value);
        });
        // 获取所有键的集合并转换为列表
        List<String> keyList = new ArrayList<>(axis.keySet());

        // 对键列表进行排序
        Collections.sort(keyList);

        // 根据排序后的键列表，从HashMap中获取对应的值列表
        List<Long> valueList = new ArrayList<>();
        for (String key : keyList) {
            valueList.add((Long) axis.get(key));
        }
        result.put("xAxis", keyList);
        result.put("yAxis", valueList);
        return JSONObject.toJSONString(result);
    }
}
